# !/usr/bin/env python
# -*- coding: utf-8 -*-

from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from mytest import models
from mytest.utils.encrypt import md5


class BootStrapModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环ModelForm中的所有字段，给每个字段的插件设置
        for name, field in self.fields.items():
            # 字段中有属性，保留原来的属性，没有属性，才增加。
            if field.widget.attrs:
                field.widget.attrs["class"] = "form-control"
                field.widget.attrs["placeholder"] = field.label
                field.widget.attrs["required"] = False
            else:
                field.widget.attrs = {
                    "class": "form-control",
                    "placeholder": field.label,
                    "required": False
                }


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)  # 加上render_value密码错误后也不会滞空，但我用的模态框，可以不加
    )

    class Meta:
        model = models.Admin
        fields = "__all__"
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_confirm_password(self):
        # print(self.cleaned_data)
        pwd = self.cleaned_data.get("password")
        confirm = self.cleaned_data.get("confirm_password")
        confirm = md5(confirm)
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # print(1)
        # 这个返回值最终也会到cleaned_data里被保存到数据库。
        return confirm

    def clean_password(self):
        # print(2)
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


# class AdminEditModelForm(BootStrapModelForm):
#     class Meta:
#         model = models.Admin
#         field_order = ["username]"]


# class AdminResetModelForm(BootStrapModelForm):
#     confirm_password = forms.CharField(
#         label="确认密码",
#         widget=forms.PasswordInput(render_value=True)
#     )
#
#     class Meta:
#         model = models.Admin
#         field_order = ["username]"]


class DepartmentModelForm(BootStrapModelForm):
    class Meta:
        model = models.Department
        fields = '__all__'


class LoginModelForm(forms.ModelForm):
    username = forms.CharField(
        label="Username"
    )
    password = forms.CharField(
        label="Password"
    )

    class Meta:
        model = models.Admin
        fields = ["username", "password"]
        widgets = {
            # "username": forms.CharField(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


class BugModelForm(BootStrapModelForm):
    class Meta:
        model = models.Bug
        fields = '__all__'  # 使用__all__默认全部，不包括自动增长的ID


class PrettyNumModelForm(BootStrapModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    )

    class Meta:
        model = models.PrettyNum
        # fields = "__all__"
        fields = ["mobile", 'price', 'level', 'status']
        # exclude = ['level']     # 排除

    def clean_mobile(self):

        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        if len(txt_mobile) != 11:
            # 验证不通过
            raise ValidationError("手机号应为11位")

        # 验证通过, 用户输入的值返回
        return txt_mobile


class UserModelForm(BootStrapModelForm):
    class Meta:
        model = models.User
        fields = "__all__"
        # exclude = ["password"]


